package com.auto.survey.activity.monitoring

import android.content.Intent
import android.text.Spannable
import android.text.SpannableString
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.viewModels
import com.auto.survey.R
import com.auto.survey.activity.bluetooth.BluetoothManagerUtil
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_OBJECT_ID
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_PROJET_ID
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_STATION_ID
import com.auto.survey.activity.monitoring.dao.MonitoringRepository
import com.auto.survey.base.BaseActivity
import com.auto.survey.widget.CentreToast
import com.auto.survey.widget.dialog.radiodialog.RadioDialogHelper
import com.didi.davinci.switcher.UISwitcher
import androidx.core.graphics.toColorInt
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_COLLECT_ID
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_MEASURE_ID
import com.auto.survey.activity.monitoring.adapter.MontoringPointAdapter
import com.auto.survey.activity.monitoring.adapter.MontoringPointAdapter.OnPointClickItemListener
import com.auto.survey.activity.monitoring.entity.MonitoringPoint
import com.auto.survey.activity.monitoring.modle.DoCollectedViewModle
import com.auto.survey.activity.monitoring.modle.DoCollectedViewModle.Companion.KEY_MAP_MIRROR_TYPE
import com.auto.survey.activity.monitoring.modle.DoCollectedViewModle.Companion.KEY_MAP_POINT_HIGHT
import com.auto.survey.activity.monitoring.modle.DoCollectedViewModle.Companion.KEY_MAP_POINT_HZ
import com.auto.survey.activity.monitoring.modle.DoCollectedViewModle.Companion.KEY_MAP_POINT_SD
import com.auto.survey.activity.monitoring.modle.DoCollectedViewModle.Companion.KEY_MAP_POINT_VA
import com.auto.survey.activity.monitoring.modle.DoCollectedViewModle.Companion.KEY_MAP_POINT_X
import com.auto.survey.activity.monitoring.modle.DoCollectedViewModle.Companion.KEY_MAP_POINT_Y
import com.auto.survey.activity.monitoring.modle.DoCollectedViewModle.Companion.KEY_MAP_POINT_Z
import com.auto.survey.activity.monitoring.point.CreatePointActivity
import com.auto.survey.activity.monitoring.point.ManagerPointActivity
import com.auto.survey.geocom.CommandContext
import com.auto.survey.geocom.GeoCom
import com.auto.survey.geocom.GeoComCommon
import com.auto.survey.geocom.GeoComHelper
import com.auto.survey.util.Helper
import com.auto.survey.widget.dialog.loadingdialog.LoadingDialog
import com.auto.survey.widget.dialog.optionsdialog.DynamicOptionsDialog
import com.auto.survey.widget.dialog.optionsdialog.OptionItem
import com.google.gson.Gson
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlin.math.PI
import kotlin.math.absoluteValue

/**
 * 学习测量
 */
class DoCollectedActivity :BaseActivity(){

    private var projectId:Int = -1
    private var objectId:Int = -1
    private var stationId:Int = -1
    private val database = MonitoringRepository()

    private lateinit var uiSwitch: UISwitcher
    private lateinit var mirrorTv: TextView
    private lateinit var pointNameTv:TextView
    private lateinit var stateTv:TextView
    private lateinit var measureTv:TextView     //测距模式
    private lateinit var mirrorTypeTv:TextView  //棱镜类型
    private lateinit var prismCorrTv:TextView// 棱镜常数
    private lateinit var changeFaceTv:TextView//盘左盘右侧切换
    private var adapter: MontoringPointAdapter? = null
    // 创建并显示加载框
    private var loadingDialog: LoadingDialog?= null

    private val viewModel: DoCollectedViewModle by viewModels()

    private var mRadioSelectIndex = -1//棱镜选择的索引
    private var prismType = "-1"    //当前测量的模式

    private var  mirrorType = "-1"  //棱镜类型

    private var isBluetoothConnected = false
    private val bluetoothManager by lazy { BluetoothManagerUtil.getInstance(this) }
    private val geoComHelper: GeoComHelper by lazy { GeoComHelper.getInstance(bluetoothManager) }

    private var mItemSelectedPoint:MonitoringPoint?=null//点击item被选中的point
    private var mSelectedPosition = -1

    private val measureMap = HashMap<String,Double>()//测量后选点用

    private var clickid = -1

    // 单例回调对象
    private var geoComCallback: ((List<GeoCom>, CommandContext) -> Unit)? = null


    override fun initView() {
        // 绑定Service
        bluetoothManager.bindService()
        uiSwitch = findViewById(R.id.switcher_docollected_atr)
        mirrorTv = findViewById(R.id.tv_docollected_mirror)
        pointNameTv = findViewById(R.id.tv_docollected_pointName)
        stateTv = findViewById(R.id.tv_docollected_state)
        measureTv = findViewById(R.id.tv_docollected_measure_modle)
        mirrorTypeTv = findViewById(R.id.tv_docollected_mirror_type)
        prismCorrTv = findViewById(R.id.tv_docollected_PrismCorr)
        changeFaceTv = findViewById(R.id.tv_docollected_learn)
        loadingDialog = LoadingDialog(this)

        initGeoComCallback()

        if (bluetoothManager.isBluetoothConnected()) {
            isBluetoothConnected = true
            //获取 ATR（自动目标识别）模式的当前状态 \ 获取当前全站仪的矫正状态 \ 获取当前全站仪的棱镜类型、棱镜常数\仪器是否整平
            geoComHelper.startExecution(listOf(GeoComCommon.AUS_GetUserAtrState, GeoComCommon.TMC_GetInclineSwitch,
                GeoComCommon.TMC_GetAngSwitch, GeoComCommon.TMC_GetPrismCorr, GeoComCommon.BAP_GetPrismType,
                GeoComCommon.TMC_GetEdmMode, GeoComCommon.TMC_GetAngle1, GeoComCommon.TMC_GetFace))
        }

        geoComHelper.onConnectionStateChanged { device, state ->
            if (bluetoothManager.isBluetoothConnected()) {
                CentreToast.instance.show("设备连接成功", true)
                isBluetoothConnected = true
                //连接成功后，获取 ATR（自动目标识别）模式的当前状态
                geoComHelper.startExecution(listOf(GeoComCommon.AUS_GetUserAtrState, GeoComCommon.TMC_GetInclineSwitch,
                    GeoComCommon.TMC_GetAngSwitch, GeoComCommon.TMC_GetPrismCorr, GeoComCommon.BAP_GetPrismType,
                    GeoComCommon.TMC_GetEdmMode, GeoComCommon.TMC_GetAngle1, GeoComCommon.TMC_GetFace))
            } else {
                isBluetoothConnected = false
            }
        }

        // 注册回调（如果尚未注册）
        if (geoComCallback != null && !geoComHelper.isRegisterCallback(geoComCallback!!)) {
            geoComHelper.resultCallback(geoComCallback!!)
        }

        projectId = intent.getIntExtra(KEY_INTENT_PROJET_ID, -1)
        objectId = intent.getIntExtra(KEY_INTENT_OBJECT_ID, -1)
        stationId = intent.getIntExtra(KEY_INTENT_STATION_ID, -1)

        mTopBar?.visibility = View.VISIBLE
        mTopBar?.setBackgroundResource(R.color.action_bar)

        mComment_title?.visibility = View.VISIBLE
        mComment_title?.setBackgroundResource(R.color.action_bar)
        mComment_title?.setTitle("学习测量")

        val rv_docollected = findViewById<RecyclerView>(R.id.rv_docollected)
        rv_docollected.layoutManager = LinearLayoutManager(this)
        adapter = MontoringPointAdapter(true, rv_docollected)
        rv_docollected.adapter = adapter
        adapter?.setOnItemClickListener(object: OnPointClickItemListener{
            override fun ontItemPointClick(point: MonitoringPoint, position:Int) {
                mItemSelectedPoint = point
                mSelectedPosition = position
                pointNameTv.text = point.pointName
            }
        })

        setClick()

        lifecycleScope.launch {
            viewModel.state.observe(this@DoCollectedActivity) {
                val pass = it[DoCollectedViewModle.KEY_DO_COLLECTED_PASS] as Boolean
                val msg = it[DoCollectedViewModle.KEY_DO_COLLECTED_MESSAGE] as String
                stateTv.text = msg
            }

            viewModel.faceState.observe(this@DoCollectedActivity) {
                loadingDialog?.dismiss()
                changeFaceTv.text = it
            }

            viewModel.mPoint.observe(this@DoCollectedActivity){
                adapter?.notifyItemChanged(mSelectedPosition)
                loadingDialog?.dismiss()
                CoroutineScope(Dispatchers.IO).launch {
                    if (mItemSelectedPoint != null) {
                        mItemSelectedPoint?.collected = true
                        database.updatePoint(mItemSelectedPoint!!)
                    }
                }
            }

            viewModel.measureData.observe(this@DoCollectedActivity) {
                if (it[KEY_MAP_POINT_HZ] != null
                    && it[KEY_MAP_POINT_VA] != null
                    && it[KEY_MAP_POINT_SD] != null
                    && it[KEY_MAP_POINT_HIGHT] != null
                    && it[KEY_MAP_POINT_X] != null
                    && it[KEY_MAP_POINT_Y] != null
                    && it[KEY_MAP_POINT_Z] != null) {
                    Log.i("DoCollectedActivity", "测量后选点，测量结束，可以跳转")
                    loadingDialog?.dismiss()

                    val intent = Intent()
                    intent.putExtra(KEY_INTENT_STATION_ID, stationId)
                    intent.putExtra(KEY_INTENT_PROJET_ID, projectId)
                    intent.putExtra(KEY_INTENT_OBJECT_ID, objectId)
                    intent.putExtra(KEY_INTENT_MEASURE_ID, Gson().toJson(it))
                    intent.setClass(this@DoCollectedActivity, ManagerPointActivity::class.java)
                    startActivity(intent)
                    measureMap.clear()
                }
            }
        }
    }

    private fun initGeoComCallback() {

        if (geoComCallback == null) {
            geoComCallback = { results, params ->

                results.forEach {
                    Log.i("DoCollectedActivity", "name = ${it.name}, command=${it.command}, result=${it.result}")
                    //获取ATR状态
                    if (GeoComCommon.AUS_GetUserAtrState.name == it.name) {
                        val list = Helper.parseJson(it.result)
                        if(list.isEmpty()){
                            return@forEach
                        }

                        if (list[1] == "1") {
                            uiSwitch.setCheckedState(true)
                        } else {
                            uiSwitch.setCheckedState(false)
                        }
                    }
                    //设置ATR开关状态
                    if (GeoComCommon.AUS_SetUserAtrState.name == it.name) {
                        val list = Helper.parseJson(it.result)
                        if(list.isEmpty()){
                            return@forEach
                        }
                        if(list[0] != "0") {
                            uiSwitch.setCheckedState(!uiSwitch.isChecked())
                        }
                    }
                    //获取当前双轴补偿器的状态，即双轴补偿器是否开启。
                    if (GeoComCommon.TMC_GetInclineSwitch.name == it.name) {
                        val list = Helper.parseJson(it.result)
                        if ("1" != list[1]){
                            val tvstat = "双轴补偿器未打开"
                            val tempText = stateTv.text
                            val str =  if(TextUtils.isEmpty(tempText)) tvstat else  "$tempText & $tvstat"
                            viewModel.updateState(false, str)
                        }
                    }
                    //获取全站仪角度测量的校正状态，包括倾斜校正、竖轴校正、视准轴校正和横轴校正。
                    if (GeoComCommon.TMC_GetAngSwitch.name == it.name) {
                        val list = Helper.parseJson(it.result)
                        val inClineCorr     = list[1]   //倾斜校正状态
                        val standAxisCorr   = list[2]   //竖轴校正状态
                        val collimationCorr = list[3]   //视准轴校正状态
                        val tiltaxisCorr    = list[4]   //横轴校正状态

                        if ("1" != inClineCorr){
                            val tvstat = "倾斜校正未打开"
                            val tempText = stateTv.text
                            val str =  if(TextUtils.isEmpty(tempText)) tvstat else  "$tempText & $tvstat"
                            viewModel.updateState(false, str)
                        }
                        if ("1" != standAxisCorr){
                            val tvstat = "竖轴校正未打开"
                            val tempText = stateTv.text
                            val str =  if(TextUtils.isEmpty(tempText)) tvstat else  "$tempText & $tvstat"
                            viewModel.updateState(false, str)
                        }
                        if ("1" != collimationCorr){
                            val tvstat = "视准轴校正未打开"
                            val tempText = stateTv.text
                            val str =  if(TextUtils.isEmpty(tempText)) tvstat else  "$tempText & $tvstat"
                            viewModel.updateState(false, str)
                        }
                        if ("1" != tiltaxisCorr){
                            val tvstat = "横轴校正未打开"
                            val tempText = stateTv.text
                            val str =  if(TextUtils.isEmpty(tempText)) tvstat else  "$tempText & $tvstat"
                            viewModel.updateState(false, str)
                        }
                    }
                    //获取当前使用的棱镜常数
                    if (GeoComCommon.TMC_GetPrismCorr.name == it.name) {
                        val list = Helper.parseJson(it.result)
                        var prismCorr = list[1]
                        if (!TextUtils.isEmpty(prismCorr)) {

                            prismCorr =  Helper.formateDecimal(prismCorr.toDouble()*100, "##.#").toString()
                        }
                        Log.i("DoCollectedActivity", "棱镜常数是：$prismCorr")
                        prismCorrTv.text = "$prismCorr(mm)"
                    }
                    //获取全站仪当前配置的棱镜类型（如单棱镜、三棱镜、免棱镜等）。
                    if (GeoComCommon.BAP_GetPrismType.name == it.name) {
                        val list = Helper.parseJson(it.result)
                        mirrorType = list[1]
                        Log.i("DoCollectedActivity", "棱镜类型是：$mirrorType")
                        var strType = ""
                        when(mirrorType) {
                            "0" -> strType = "圆棱镜"
                            "1" -> strType = "迷你棱镜"
                            "2" -> strType = "反射片"
                        }
                        mirrorTypeTv.text = strType
                    }
                    //获取全站仪的电子测距（EDM）模式，了解当前仪器采用的测距方式。
                    if (GeoComCommon.TMC_GetEdmMode.name == it.name) {
                        val list = Helper.parseJson(it.result)
                        prismType = list[1]
                        Log.i("DoCollectedActivity", "测量模式是：$prismType")
                        var strType = ""
                        when(prismType) {
                            "0" -> strType = "标准"
                            "1" -> strType = "快速"
                            "2" -> strType = "高精"
                            "3" -> strType = "跟踪"
                        }
                        measureTv.text = strType
                    }
                    //在配置或定义的 ATR 搜索窗口内搜索目标。
                    if (GeoComCommon.BAP_SearchTarget.name == it.name) {
                        if (it.result == "-1") {
                            viewModel.updateState(false, "未找到目标")
                            loadingDialog?.dismiss()
                        } else {
                            viewModel.updateState(false, "已找到目标")

                            //用于选点后测量 和 测量后选点
                            if (prismType != "-1") {
                                geoComHelper.startExecution(listOf(GeoComCommon.BAP_MeasDistanceAngle(prismType),
                                    GeoComCommon.TMC_GetHeight, GeoComCommon.TMC_GetCoordinate("1", "5000")))

                                return@forEach
                            }

                        }
                    }
                    //设备是否整平
                    if (GeoComCommon.TMC_GetAngle1.name == it.name) {
                        if (it.result == "-1") {
                            viewModel.updateState(false, "设备未整平，请手动整平")
                        } else {
                            val list = Helper.parseJson(it.result)
                            val hz = list[1]
                            val v = list[2]
                            val crossIncline = list[5]      //双精度横向倾角（单位：弧度）
                            val lengthIncline = list[6]     //双精度横向倾角（单位：弧度）
                            val strT = Helper.radiansToDMSString(crossIncline.toDouble())
                            val strL = Helper.radiansToDMSString(lengthIncline.toDouble())

                            val secT = Helper.radiansToSecond(crossIncline.toDouble()).absoluteValue
                            val secL = Helper.radiansToSecond(lengthIncline.toDouble()).absoluteValue

                            if ( secT<180  &&  secL < 180) {
                                val msg = "L:$strL ,  T:$strT"
                                viewModel.updateState(true, msg)
                            } else {
                                val msg = "未达到整平要求范围"
                                viewModel.updateState(false, msg)
                            }


                            if (clickid == R.id.tv_docollected_more) {
                                //用户点击了更多中的旋转180度操作，旋转180度之前，需要先查询TMC_GetAngle1命令，根据当前结果来旋转
                                loadingDialog?.dismiss()
                                val target = (hz.toDouble() + PI).toString()
                                geoComHelper.startExecution(listOf(GeoComCommon.AUT_MakePositioning(target, v)))
                            }

                        }

                    }

                    //用于单次测量水平角（Hz）、垂直角（V）和斜距（dDist）
                    if (GeoComCommon.BAP_MeasDistanceAngle.name == it.name) {
                        //["0","0.531449903201491","1.621547645107979","2.962120866183635","2"]
                        val list = Helper.parseJson(it.result)
                        val strHz = Helper.radiansToDMSString(list[1].toDouble())
                        val strV =  Helper.radiansToDMSString(list[2].toDouble())
                        val strDist = Helper.formateDecimal(list[3].toDouble(), "#.####")
                        Log.i("DoCollectedActivity", "获取当前测点水平角度:$strHz, 垂直角：$strV, 斜距：$strDist")

                        if (clickid != -1 && clickid == R.id.tv_docollected_choice_measure && mSelectedPosition != -1) {
                            //用于选点后测量
                            mItemSelectedPoint?.pointHz = list[1].toDouble()
                            mItemSelectedPoint?.pointV = list[2].toDouble()
                            mItemSelectedPoint?.pointSD = strDist
                            mItemSelectedPoint?.mirrorType = mirrorType.toInt()
                            viewModel.updatePoint(mItemSelectedPoint)
                        }

                        if(clickid != -1 && clickid == R.id.tv_docollected_measure_choice) {
                            //用于测量后选点
                            measureMap[KEY_MAP_POINT_HZ] = list[1].toDouble()
                            measureMap[KEY_MAP_POINT_VA] = list[2].toDouble()
                            measureMap[KEY_MAP_POINT_SD] = strDist
                            measureMap[KEY_MAP_MIRROR_TYPE] = mirrorType.toDouble()
                            viewModel.updateMeasureData(measureMap)
                        }


                    }
                    // 切换盘左盘右
                    if (GeoComCommon.AUT_ChangeFace.name == it.name) {
                        loadingDialog?.dismiss()
                        if (it.result != "-1" ) {
                            val list = Helper.parseJson(it.result)
                            if (list[0] == "0") {
                                geoComHelper.startExecution(listOf(GeoComCommon.TMC_GetFace))
                            }
                        }
                    }
                    //获取盘左 盘右。
                    if (GeoComCommon.TMC_GetFace.name == it.name) {
                        //["0","0"]
                        val list = Helper.parseJson(it.result)
                        if (list[1] == "0") {
                            Log.i("DoCollectedActivity", "当前是盘左")
                            viewModel.updateFaceMsg("切换盘右")
                        } else {
                            Log.i("DoCollectedActivity", "当前是盘右")
                            viewModel.updateFaceMsg("切换盘左")
                        }
                    }

                    //获取棱镜高度
                    if(GeoComCommon.TMC_GetHeight.name == it.name) {
                        //["0","0"]
                        val list = Helper.parseJson(it.result)
                        Log.i("DoCollectedActivity", "当前测点棱镜高度是${list[1]} 米")
                        if (clickid != -1 && clickid == R.id.tv_docollected_choice_measure && mSelectedPosition != -1) {
                            //用于选点后测量
                            mItemSelectedPoint?.mirrorHeight = list[1].toDouble()
                            viewModel.updatePoint(mItemSelectedPoint)
                        }
                        if(clickid != -1 && clickid == R.id.tv_docollected_measure_choice) {
                            //用于测量后选点
                            measureMap[KEY_MAP_POINT_HIGHT] = list[1].toDouble()
                            viewModel.updateMeasureData(measureMap)
                        }

                    }

                    //获取坐标
                    if(GeoComCommon.TMC_GetCoordinate.name == it.name) {
                        //["0","860.54986327096356","1393.1747212830203","12.887774814205464","4858320","860.54986327096356","1393.1747212830203","12.887774814205464","4858320"]
                        val list = Helper.parseJson(it.result)
                        val strE = Helper.formateDecimal(list[1].toDouble(), "#.####")
                        val strN = Helper.formateDecimal(list[2].toDouble(), "#.####")
                        val strZ = Helper.formateDecimal(list[3].toDouble(), "#.####")
                        Log.i("DoCollectedActivity", "获取当前测点坐标， X/北N(m):$strN, Y/东E(m)：$strE, Z/高H(m)：$strZ")
                        if (clickid != -1 && clickid == R.id.tv_docollected_choice_measure && mSelectedPosition != -1)  {
                            //用于选点后测量
                            mItemSelectedPoint?.pointX = strN
                            mItemSelectedPoint?.pointY = strE
                            mItemSelectedPoint?.pointZ = strZ
                            mItemSelectedPoint?.mirrorType = mirrorType.toInt()
                            viewModel.updatePoint(mItemSelectedPoint)
                        }

                        if(clickid != -1 && clickid == R.id.tv_docollected_measure_choice){
                            //用于测量后选点
                            measureMap[KEY_MAP_POINT_X] = strN
                            measureMap[KEY_MAP_POINT_Y] = strE
                            measureMap[KEY_MAP_POINT_Z] = strZ
                            measureMap[KEY_MAP_MIRROR_TYPE] = mirrorType.toDouble()
                            viewModel.updateMeasureData(measureMap)
                        }

                    }
                }
            }
        }

    }

    private fun setClick(){
        //ATR
        uiSwitch.setOnCheckedChangeListener(UISwitcher.OnCheckedChangeListener { buttonView, isChecked ->
            if (!isBluetoothConnected) {
                CentreToast.instance.show("请先连接仪器", false)
                uiSwitch.setCheckedState(true, !uiSwitch.isChecked())
                return@OnCheckedChangeListener
            }

            //设置 ATR（自动目标识别）模式的当前状态
            geoComHelper.startExecution(listOf(GeoComCommon.AUS_SetUserAtrState(isChecked)))

        })
        //反射介质
        mirrorTv.setOnClickListener{
            if (!isBluetoothConnected) {
                CentreToast.instance.show("请先连接仪器", false)
                return@setOnClickListener
            }

            RadioDialogHelper.Builder(this)
                .setTitle("请选择")
                .setItems(listOf(
                    RadioDialogHelper.RadioBean(0x3001, "徕卡圆棱镜"),
                    RadioDialogHelper.RadioBean(0x3002, "徕卡小棱镜"),
                    RadioDialogHelper.RadioBean(0x3002, "徕卡反射片")))
                .setSelectedIndex(mRadioSelectIndex)
                .setOnItemSelectedListener { position, radioBean ->
                    mRadioSelectIndex = position
                    Log.i("DoCollectedActivity", "反射介质: ${radioBean.content}, position = $position")
                    val text = "反射介质 ${radioBean.content}"
                    val spannableString = SpannableString(text)
                    spannableString.setSpan(ForegroundColorSpan("#4c4c4c".toColorInt()), 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                    spannableString.setSpan(ForegroundColorSpan("#C80505".toColorInt()), 4, text.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                    mirrorTv.text = spannableString

                    //根据选择的反射介质，测距模式、

                    if (position == 0) {
                        //徕卡圆棱镜       测距模式：高精度模式     棱镜类型 0
                        geoComHelper.startExecution(listOf(GeoComCommon.BAP_SetPrismType("0"),  GeoComCommon.TMC_SetEdmMode(),
                            GeoComCommon.BAP_GetPrismType, GeoComCommon.TMC_GetEdmMode, GeoComCommon.TMC_GetPrismCorr))
                    }

                    if (position == 1) {
                        //徕卡小棱镜       测距模式：标准模式       棱镜类型 1
                        geoComHelper.startExecution(listOf(GeoComCommon.BAP_SetPrismType("1"),  GeoComCommon.TMC_SetEdmMode(),
                            GeoComCommon.BAP_GetPrismType, GeoComCommon.TMC_GetEdmMode, GeoComCommon.TMC_GetPrismCorr))
                    }

                    if (position == 2) {
                        //注意：设置模式如果是高精度模式，全站仪会自动把介质置为圆棱镜
                        //徕卡反射片       测距模式：标准模式       棱镜类型 2
                        geoComHelper.startExecution(listOf(GeoComCommon.BAP_SetPrismType("2"), GeoComCommon.TMC_SetEdmMode("1"),
                            GeoComCommon.BAP_GetPrismType, GeoComCommon.TMC_GetEdmMode, GeoComCommon.TMC_GetPrismCorr))
                    }

                }.build().show()


        }
        //关闭激光
        findViewById<ImageView>(R.id.iv_tv_docollected_lightoff).setOnClickListener {
            if (!isBluetoothConnected) {
                CentreToast.instance.show("请先连接仪器", false)
                return@setOnClickListener
            }

            geoComHelper.startExecution(listOf(GeoComCommon.EDM_Laserpointer(false)))
        }
        //开启激光
        findViewById<ImageView>(R.id.iv_tv_docollected_lighton).setOnClickListener {
            if (!isBluetoothConnected) {
                CentreToast.instance.show("请先连接仪器", false)
                return@setOnClickListener
            }

            geoComHelper.startExecution(listOf(GeoComCommon.EDM_Laserpointer(true)))
        }
        //搜索目标
        findViewById<TextView>(R.id.tv_docollected_search).setOnClickListener {
            if (!isBluetoothConnected) {
                CentreToast.instance.show("请先连接仪器", false)
                return@setOnClickListener
            }
            geoComHelper.startExecution(listOf(GeoComCommon.BAP_SearchTarget))
        }

        //选点后测量
        findViewById<TextView>(R.id.tv_docollected_choice_measure).setOnClickListener {
            clickid = R.id.tv_docollected_choice_measure
            if (!isBluetoothConnected) {
                CentreToast.instance.show("请先连接仪器", false)
                return@setOnClickListener
            }
            if (mRadioSelectIndex == -1) {
                CentreToast.instance.show("请先选择反射介质", false)
                return@setOnClickListener
            }

            if (mSelectedPosition == -1) {
                CentreToast.instance.show("请选择测点", false)
                return@setOnClickListener
            }

            loadingDialog?.show()
            //搜索目标
            geoComHelper.startExecution(listOf(GeoComCommon.BAP_SearchTarget))
        }

        //测量后选点
        findViewById<TextView>(R.id.tv_docollected_measure_choice).setOnClickListener {
            clickid = R.id.tv_docollected_measure_choice
            if (!isBluetoothConnected) {
                CentreToast.instance.show("请先连接仪器", false)
                return@setOnClickListener
            }
            if (mRadioSelectIndex == -1) {
                CentreToast.instance.show("请先选择反射介质", false)
                return@setOnClickListener
            }
            loadingDialog?.show()
            //搜索目标
            geoComHelper.startExecution(listOf(GeoComCommon.BAP_SearchTarget))
        }

        //刻盘置为零
        findViewById<TextView>(R.id.tv_docollected_choice_point).setOnClickListener {
            if (!isBluetoothConnected) {
                CentreToast.instance.show("请先连接仪器", false)
                return@setOnClickListener
            }
            //刻盘置为零
            geoComHelper.startExecution(listOf(GeoComCommon.TMC_SetOrientation))
        }
        //输点
        findViewById<TextView>(R.id.tv_docollected_add_point).setOnClickListener {
            if (!isBluetoothConnected) {
                CentreToast.instance.show("请先连接仪器", false)
                return@setOnClickListener
            }

            val intent = Intent()
            intent.putExtra(KEY_INTENT_OBJECT_ID, objectId)
            intent.putExtra(KEY_INTENT_STATION_ID, stationId)
            intent.putExtra(KEY_INTENT_COLLECT_ID, true)
            intent.setClass(this@DoCollectedActivity, CreatePointActivity::class.java)
            startActivity(intent)

        }

        //切换盘左盘右
        changeFaceTv.setOnClickListener {
            if (!isBluetoothConnected) {
                CentreToast.instance.show("请先连接仪器", false)
                return@setOnClickListener
            }

            loadingDialog?.show()
            geoComHelper.startExecution(listOf(GeoComCommon.AUT_ChangeFace))

        }

        findViewById<TextView>(R.id.tv_docollected_more).setOnClickListener {
            if (!isBluetoothConnected) {
                CentreToast.instance.show("请先连接仪器", false)
                return@setOnClickListener
            }

            // 创建带图标的选项
            val options = listOf(
                OptionItem(1, "水平旋转180", R.mipmap.sy_cmfb),
                OptionItem(2, "定时开机", R.mipmap.sy_tg),
                OptionItem(3, "定时关机", R.mipmap.sy_gshyl),
                OptionItem(4, "棱镜管理", R.mipmap.sy_nihuigou),
                OptionItem(5, "设置测回数", R.mipmap.sy_gupiaochicang)
            )

            // 显示对话框
            DynamicOptionsDialog.Builder(this)
                .setTitle("更多操作")
                .setOptions(options)
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .setOnOptionSelectedListener { option ->
                    when (option.id) {
                        1 -> {
                            clickid = R.id.tv_docollected_more
                            loadingDialog?.show()
                            geoComHelper.startExecution(listOf(GeoComCommon.TMC_GetAngle1))
                        }
                        2 -> CentreToast.instance.show("暂未开发", false)
                        3 -> CentreToast.instance.show("暂未开发", false)
                        4 -> CentreToast.instance.show("暂未开发", false)
                        5 -> CentreToast.instance.show("暂未开发", false)
                    }
                }
                .show()

        }
    }

    override fun onResume() {
        super.onResume()
        lifecycleScope.launch {
            Log.i("DoCollectedActivity", "objectId = $objectId, stationId = $stationId")
            database.getMonitoringPointClloectedByStationId(stationId).collect{
                adapter?.setData(it)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.i("DoCollectedActivity", "####onDestroy###")
        geoComHelper.removeResultCallback(geoComCallback!!)
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_docollected
    }

}